/*****************************************************************************
 * NetGetLogin :  returns UID of connection
 * Author:        Simon Amor <simon@foobar.net>
 * If returns a NULL for UID, connection failed, check return value.
 * Else, UID points to a static buffer containing UID
 * Return values:
 *  0 = ok
 *  1 = socket failure
 *  2 = unknown host
 *  3 = information unobtainable - possibly no ident server
 *  4 = invalid ports specified
 *  5 = 
 ***/
int NetGetLogin(char *RemoteHost,int LocalPort,int RemotePort, char *uid)
{
  int fd,params;
  struct hostent *hp;
  struct servent *sp;
  struct sockaddr_in addr;
  int addrlen;
  FILE *fp_in, *fp_out;
  char buffer[8192], reply_type[81], opsys_or_error[81];
  char identifier[1024], charset[81], opsys[81];
  static char uidBuffer[10];

  uid=NULL;

  if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)
    return 1;

  addr.sin_family = AF_INET;
  if (isdigit(remote_host[0]))
    addr.sin_addr.s_addr = inet_addr(remote_host);
  else
  {
    if ((hp = gethostbyname(remote_host)) == NULL)
      return 2;
    memcpy(&addr.sin_addr, hp->h_addr, sizeof(addr.sin_addr));
  }
  addr.sin_port = htons(113);          /* IDENT port */
  addrlen = sizeof(addr);

  if (connect(fd, &addr, addrlen) == -1)
    return 3;
  if (getsockname(fd, &addr, &addrlen) == -1)
    return 3;

  fp_in  = fdopen(fd, "r");
  fp_out = fdopen(fd, "w");
  if (!fp_in || !fp_out)
    return 3;

  fprintf(fp_out, "%d , %d\n", lport, fport);
  fflush(fp_out);
  shutdown(fd, 1);

  if (fgets(buffer, sizeof(buffer)-1, fp_in) == NULL)
    return 3;

  params = sscanf(buffer, " %d , %d : %[^ \t\n\r:] : %[^\t\n\r:] : %[^\n\r]",
		&lport, &fport, reply_type, opsys_or_error, identifier);
  if (params < 3)
    return 3;

  opsys[0] = charset[0] = '\0';
  if (sscanf(opsys_or_error, " %s , %s", opsys, charset) != 2)
    strcpy(opsys, opsys_or_error);
  
  if (strcasecmp(reply_type, "ERROR") == 0)
  {
    if (strcasecmp(opsys_or_error, "INVALID-PORT") == 0)
      fprintf(stderr, "invalid port(s) specified (%d , %d)\n",
              lport, fport);
    else if (strcasecmp(opsys_or_error, "NO-USER") == 0)
      fprintf(stderr, "connection not in use (%d , %d)\n",
              lport, fport);
    else if (strcasecmp(opsys_or_error, "UNKNOWN-ERROR") == 0)
      fprintf(stderr, "unknown error\n");
    else if (strcasecmp(opsys_or_error, "USER-REJECTED") == 0)
      fprintf(stderr, "user rejected\n");
    else
      fprintf(stderr, "unknown error: %s\n",opsys_or_error);
    return 2;
  }
  else if (strcasecmp(reply_type, "USERID") != 0)
  {
    fprintf(stderr, "protocol error: %s\n", reply_type);
    return -4;
  }
  strcpy(global_string,&identifier);
  fclose(fp_out);
  fclose(fp_in);
  return 0;
}
